<template>
  <div class="autoform-advanced-expression-wrapper">
    <div class="advanced-expression-group-toolbar">
      <el-button size="small" @click="resetExpressionItems()" type="danger" plain>
        {{ i18nt("designer.hint.formulaClear") }}
      </el-button>
    </div>
    <div class="advanced-expression-group-body">
      <div class="advanced-expression-group-item" v-for="(item, index) in modelValue" :key="item.id">
        <template v-if="index !== (modelValue.length - 1)">
          <div class="advanced-expression-actions">
            <el-icon style="color: #409eff;" @click="handleAddExpressionItem(index)"><CirclePlus /></el-icon>
            <el-icon v-if="showExpressionItemRemoveBtn" style="color: #f56c6c;" @click="handleRemoveExpressionItem(item)"><Remove /></el-icon>
          </div>
          <div class="advanced-expression-left-label">如果</div>
          <div class="advanced-expression-left-textarea">
            <el-input :model-value="item.condition" type="textarea" :rows="3" resize="none" placeholder="点击设置内容" readonly
                      @click="handleSetExpressionItemValue(item, 'condition')" />
          </div>
        </template>
        <div class="advanced-expression-right-label">
          {{ index !== (modelValue.length - 1) ? "则为" : "否则为" }}
        </div>
        <div class="advanced-expression-right-textarea">
          <el-input :model-value="item.content" type="textarea" :rows="3" resize="none" placeholder="点击设置内容" readonly
                    @click="handleSetExpressionItemValue(item, 'content')" />
        </div>
      </div>
    </div>

    <el-dialog class="small-padding-dialog" v-model="visibleExpressionEditor" title="计算条件设置" width="70%" draggable
               :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true" :append-to-body="true">
      <expression-editor ref="simpleExpressionEditorRef" style="height: 500px;" v-model="editingRecord[editingProp]"
                         :designer="designer" :ignoredFields="ignoredFields" :simple="editingExpressionIsSimple" />

      <template #footer>
        <div class="dialog-footer">
          <el-button size="default" type="primary" @click="handleExpressionEditorOk">{{ i18nt("designer.hint.confirm") }}</el-button>
          <el-button size="default" @click="handleExpressionEditorCancel">{{ i18nt("designer.hint.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import { cloneDeep, isNumber } from "lodash";
  import { v4 as uuidv4 } from "uuid";
  import i18n from "@/utils/i18n";
  import ExpressionEditor from "./index.vue";
  import ExpressionUtil from "@/utils/expression-util";

  export default {
    name: "AdvancedExpressionEditor",
    mixins: [ i18n ],
    components: { ExpressionEditor },
    emits: [ "update:modelValue", "change" ],
    props: {
      modelValue: { type: Array, default: () => ([]) },
      designer: { type: Object, default: () => ({}) },
      ignoredFields: { type: Array, default: () => ([]) },
    },
    data() {
      return {
        visibleExpressionEditor: false,
        editingRecord: {},
        editingProp: "",
      }
    },
    computed: {
      showExpressionItemRemoveBtn() {
        return this.modelValue.length > 2;
      },
      editingExpressionIsSimple() {
        return this.editingProp === "content";
      }
    },
    methods: {
      /**
       * 新增表达式分组项
       */
      handleAddExpressionItem(insertIndex) {
        if (isNumber(insertIndex) && insertIndex >= 0) {
          const newModelValue = cloneDeep(this.modelValue);
          newModelValue.splice(insertIndex + 1, 0, {
            id: uuidv4(),
            condition: "",
            content: ""
          });
          this.$emit("update:modelValue", newModelValue);
        }
      },

      /**
       * 删除表达式分组项
       */
      handleRemoveExpressionItem(record) {
        this.$emit("update:modelValue", this.modelValue.filter((item) => (item.id !== record.id)));
      },

      /**
       * 设置指定分组表达式内容
       */
      handleSetExpressionItemValue(record, prop) {
        this.visibleExpressionEditor = true;
        this.editingRecord = cloneDeep(record);
        this.editingProp = prop;
        this.$nextTick(() => {
          this.$refs.simpleExpressionEditorRef?.init();
        });
      },

      /**
       * 重置表达式所有分组
       */
      resetExpressionItems() {
        this.$emit("update:modelValue", [
          { id: uuidv4(), condition: "", content: "" },
          { id: uuidv4(), content: "" }
        ]);
      },

      /**
       * 条件编辑器对话框确认回调
       */
      handleExpressionEditorOk() {
        this.$emit("update:modelValue", this.modelValue.map((item) => {
          if (item.id !== this.editingRecord.id) {
            return item;
          } else {
            return { ...item, [this.editingProp]: this.editingRecord[this.editingProp] };
          }
        }));
        this.visibleExpressionEditor = false;
      },

      /**
       * 条件编辑器对话框取消回调
       */
      handleExpressionEditorCancel() {
        this.visibleExpressionEditor = false;
      }
    }
  }
</script>

<style lang="scss" scoped>
  .autoform-advanced-expression-wrapper {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    gap: 5px;

    .advanced-expression-group-toolbar {
      text-align: right;
    }

    .advanced-expression-group-body {
      flex: 1;
      padding: 0 10px;
      overflow: auto;
    }

    .advanced-expression-group-item {
      line-height: 24px;
      display: flex;
      flex-direction: row;
      align-items: start;
      justify-content: end;
      gap: 5px;

      &:not(:last-child) {
        margin-bottom: 10px;
      }

      .advanced-expression-actions {
        padding: 2px 0 0;
        width: 20px;
        font-size: 18px;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 5px;

        :deep() .el-icon {
          cursor: pointer;
        }
      }

      .advanced-expression-left-label,
      .advanced-expression-right-label {
        text-align: right;
      }

      .advanced-expression-left-label {
        width: 3em;
      }

      .advanced-expression-right-label {
        width: 4em;
      }

      .advanced-expression-left-textarea,
      .advanced-expression-right-textarea {
        width: calc((100% - 8.5em - 4*5px)/2);
      }
    }
  }
</style>
